<template>
    <div class="user-info-container">
        <el-card class="form-card">
            <div class="title">完善个人信息</div>

            <!-- 头像上传区域 -->
            <div class="avatar-upload-wrapper">
                <input type="file" ref="fileInput" accept="image/*" @change="handleFileChange" hidden>
                <div class="avatar-preview" @click="triggerFileInput">
                    <img v-if="form.headPicture" :src="form.headPicture" class="avatar-image">
                    <div v-else class="upload-placeholder">
                        <i class="el-icon-plus"></i>
                        <span>点击上传头像</span>
                    </div>
                </div>
            </div>

            <!-- 信息表单 -->
            <el-form :model="form" :rules="rules" ref="infoForm" label-width="100px" label-position="top">
                <el-form-item label="昵称" prop="name">
                    <el-input v-model="form.name" placeholder="2-12个字符" clearable maxlength="12" show-word-limit />
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                        <el-radio :label="0">保密</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="手机号" prop="mobilePhone">
                    <el-input v-model="form.mobilePhone" placeholder="11位手机号码" maxlength="11" clearable />
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="6-16位字母数字组合" show-password />
                </el-form-item>

                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="form.checkPass" type="password" placeholder="再次输入密码" show-password />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="loading" size="large">
                        保存修改
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>


    </div>
</template>

<script>
import { getById, updateUser } from '@/api/user/user'
import { upload } from '@/api/common/common'

export default {
    data() {
        const validatePassword = (rule, value, callback) => {
            if (value && !/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/.test(value)) {
                callback(new Error('需包含字母和数字，6-16位'))
            } else {
                callback()
            }
        }

        const validateConfirm = (rule, value, callback) => {
            if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        }

        return {
            loading: false,
            cropDialogVisible: false,
            tempAvatar: '',
            form: {
                headPicture: '',
                name: '',
                gender: 0,
                mobilePhone: '',
                password: '',
                checkPass: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur' }
                ],
                mobilePhone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                password: [
                    { validator: validatePassword, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: validateConfirm, trigger: 'blur' }
                ]
            }
        }
    },
    mounted() {
        this.loadUserData()
    },
    methods: {
        // 触发文件选择
        triggerFileInput() {
            this.$refs.fileInput.click()
        },


        async handleFileChange(e) {
            console.log("amizimaizmaimaizamiaamzi");

            const file = e.target.files[0];
            if (!file) return;

            // 验证文件类型和大小
            if (!this.validateFile(file)) return;

            try {
                // 显示加载状态
                const loading = this.$loading({
                    lock: true,
                    text: '上传中...',
                    spinner: 'el-icon-loading'
                });

                // 执行上传
                const res = await upload(file);
                console.log(res, "res")
                this.form.headPicture = res
                loading.close();
                // 更新头像地址
                this.SET_AVATAR(res.data.url);

                this.$message.success('头像更新成功');
            } catch (error) {
                this.$message.error(`上传失败: ${error.message}`);
                loading.close();
            } finally {
                // 清空输入框以便重复上传
                e.target.value = '';
            }
        },
        validateFile(file) {
            const validTypes = ['image/jpeg', 'image/png'];
            const maxSizeMB = 2;

            if (!validTypes.includes(file.type)) {
                this.$message.error('仅支持 JPG/PNG 格式');
                return false;
            }

            if (file.size > maxSizeMB * 1024 * 1024) {
                this.$message.error(`文件大小不能超过 ${maxSizeMB}MB`);
                return false;
            }

            return true;
        },
        // 加载用户数据
        async loadUserData() {
            try {
                const { data } = await getById()
                this.form = {
                    ...data,
                    password: '',
                    checkPass: ''
                }
            } catch (error) {
                console.error('数据加载失败:', error)
            }
        },

        // 提交表单
        async submitForm() {
            try {
                const valid = await this.$refs.infoForm.validate()
                if (!valid) return

                this.loading = true
                const { checkPass, ...submitData } = this.form

                // 密码为空时不更新
                if (!submitData.password) delete submitData.password

                await updateUser(submitData)
                this.$message.success('信息更新成功')
                this.loadUserData()
            } catch (error) {
                console.error('提交失败:', error)
            } finally {
                this.loading = false
            }
        }
    }
}
</script>

<style lang="less" scoped>
.user-info-container {
    max-width: 800px;
    margin: 40px auto;
    padding: 0 20px;

    .form-card {
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        padding: 40px;

        .title {
            font-size: 24px;
            font-weight: 500;
            color: #303133;
            text-align: center;
            margin-bottom: 40px;
            position: relative;
            padding-bottom: 15px;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 60px;
                height: 3px;
                background: #409EFF;
            }
        }
    }

    .avatar-upload-wrapper {
        text-align: center;
        margin-bottom: 40px;

        .avatar-preview {
            width: 160px;
            height: 160px;
            border: 2px dashed #dcdfe6;
            border-radius: 50%;
            margin: 0 auto;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;

            &:hover {
                border-color: #409EFF;
                transform: scale(1.05);
                box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
            }

            .avatar-image {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .upload-placeholder {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #8c939d;
                background: #f8f9fa;

                i {
                    font-size: 28px;
                    margin-bottom: 8px;
                }

                span {
                    font-size: 14px;
                }
            }
        }
    }

    ::v-deep .el-form {
        .el-form-item {
            margin-bottom: 28px;

            &__label {
                font-size: 14px;
                color: #606266;
                padding-bottom: 8px;
                font-weight: 500;
            }

            .el-input {
                &__inner {
                    height: 44px;
                    border-radius: 6px;
                    transition: border-color 0.3s;

                    &:focus {
                        border-color: #409EFF;
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
                    }
                }
            }

            .el-radio-group {
                display: flex;
                gap: 30px;

                .el-radio {
                    margin-right: 0;

                    &__input.is-checked+.el-radio__label {
                        color: #409EFF;
                    }
                }
            }
        }

        .el-button--primary {
            width: 100%;
            height: 48px;
            font-size: 16px;
            transition: all 0.3s;

            &:hover {
                background: #66b1ff;
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
            }
        }
    }
}

@media (max-width: 768px) {
    .user-info-container {
        margin: 20px 0;
        padding: 0 10px;

        .form-card {
            padding: 25px;

            .title {
                font-size: 20px;
                margin-bottom: 30px;
            }
        }

        .avatar-upload-wrapper {
            .avatar-preview {
                width: 120px;
                height: 120px;
            }
        }
    }
}
</style>